import java.util.ArrayList;
import java.util.List;

class Solution10 {

    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    int m, n;

    public List<List<Integer>> pacificAtlantic(int[][] heights) {
        m = heights.length; n = heights[0].length;
        boolean[][] pac = new boolean[m][n];
        boolean[][] atl = new boolean[m][n];
        List<List<Integer>> ret = new ArrayList<>();

        for(int i = 0; i < m; i++){
            dfs(heights, i, 0, pac);
            dfs(heights, i, n - 1, atl);
        }
        for(int j = 0; j < n; j++){
            dfs(heights, 0, j, pac);
            dfs(heights, m - 1, j, atl);
        }

        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(pac[i][j] && atl[i][j]){
                    List<Integer> tmp = new ArrayList<>();
                    tmp.add(i); tmp.add(j);
                    ret.add(tmp);
                }
            }
        }
        return ret;
    }

    public void dfs(int[][] heights, int i, int j, boolean[][] ocean){
        ocean[i][j] = true;

        for(int k = 0; k < 4; k++){
            int x = i + dx[k], y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && heights[i][j] <= heights[x][y] && !ocean[x][y]){
                dfs(heights, x, y, ocean);
            }
        }
    }
}